package controller

import (
	"fmt"
	"heartbeat/database"
	"heartbeat/utils"
	"log"
	"strconv"
	"strings"
	"sync"
	"time"
)

func GetTimeoutVPS() ([]*StoreValue, error) {
	redis := database.GetRedisClient()
	config := utils.GetConfig()
	other := config.Other
	interval, err := redis.Get("alarm:interval").Int64()
	if err != nil {
		return nil, err
	}
	now := time.Now().Unix()
	shouldTime := now - interval*60

	redisKey := fmt.Sprintf(other["redisprefix"], "*")
	result := redis.Keys(redisKey)
	if result.Err() != nil {
		return nil, result.Err()
	}
	keys, _ := result.Result()
	var wg sync.WaitGroup
	wg.Add(len(keys))
	respQueue := []*StoreValue{}
	for _, key := range keys {
		go func(key string) {
			defer wg.Done()
			hValue := redis.HGetAll(key)
			if hValue.Err() != nil {
				log.Fatalln(key, hValue.Err())
			}
			storeValueInRedis := hValue.Val()
			storeValue := new(StoreValue)
			storeValue.IP = storeValueInRedis["ip"]
			storeValue.Time, _ = strconv.ParseInt(storeValueInRedis["time"], 10, 64)
			storeValue.ID = strings.Replace(key, fmt.Sprintf(other["redisprefix"], ""), "", -1)
			if shouldTime > storeValue.Time {
				respQueue = append(respQueue, storeValue)
			}
		}(key)
	}
	wg.Wait()
	return respQueue, nil
}
